﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Web;
using FSY.API.Utilities;
namespace FSY.API.Files
{
    /// <summary>
    /// Tap hop cac function lien qua den File va Thu muc
    /// </summary>
    public class Fsy_FileController
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="extension"></param>
        /// <returns></returns>
        public static string GetContentType(string extension)
        {
            switch (extension.ToLower())
            {
                case "txt":
                    return "text/plain";
                case "htm":
                case "html":
                    return "text/html";
                case "rtf":
                    return "text/richtext";
                case "jpg":
                case "jpeg":
                    return "image/jpeg";
                case "gif":
                    return "image/gif";
                case "bmp":
                    return "image/bmp";
                case "mpg":
                case "mpeg":
                    return "video/mpeg";
                case "avi":
                    return "video/avi";
                case "flv":
                case "swf":
                    return "application/x-shockwave-flash";
                case "pdf":
                    return "application/pdf";
                case "doc":
                case "dot":
                    return "application/msword";
                case "csv":
                case "xls":
                case "xlt":
                    return "application/x-msexcel";
            }
            return "application/octet-stream";
        }
        /// <summary>
        /// Kiem tra kieu file.
        /// </summary>
        /// <param name="fileName">file can kiem tra</param>
        /// <param name="extension">kieu de kiem tra</param>
        /// <returns></returns>
        public static bool IsContentType(string fileName, string[] extension)
        {
            string[] ext = fileName.Split('.');
            if (ext != null && ext.Length > 0)
            {
                if (extension.Length == 1 && extension[0] == "*.*")
                    return true;
                for (int i = 0; i < extension.Length; i++)
                {
                    if (extension[i].ToLower().Equals(ext[1]))
                        return true;
                }
                return false;
            }
            return false;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileLocation"></param>
        public static void DownloadFile(string fileLocation)
        {
            FileInfo fileInfo = new FileInfo(fileLocation);
            HttpResponse response = HttpContext.Current.Response;
            string name = fileInfo.Name;
            if (HttpContext.Current.Request.UserAgent.IndexOf("; MSIE") > 0)
            {
                name = HttpUtility.UrlEncode(name);
            }
            if (fileInfo.Exists)
            {
                response.ClearContent();
                response.ClearHeaders();
                response.AppendHeader("content-disposition", "attachment; filename=\"" + name + "\"");
                response.AppendHeader("Content-Length", fileInfo.Length.ToString());
                response.ContentType = GetContentType(fileInfo.Extension.Replace(".", ""));
                WriteFile(fileInfo.FullName);
                response.Flush();
                response.End();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strFileName"></param>
        public static void WriteFile(string strFileName)
        {
            HttpResponse objResponse = HttpContext.Current.Response;
            Stream objStream = null;
            try
            {
                objStream = new FileStream(strFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                WriteStream(objResponse, objStream);
            }
            catch (Exception exception1)
            {
                ProjectData.SetProjectError(exception1);
                Exception exception = exception1;
                objResponse.Write("Error : " + exception.Message);
                ProjectData.ClearProjectError();
            }
            finally
            {
                if (!Information.IsNothing(objStream))
                {
                    objStream.Close();
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="objResponse"></param>
        /// <param name="objStream"></param>
        private static void WriteStream(HttpResponse objResponse, Stream objStream)
        {
            byte[] buffer = new byte[0x2711];
            try
            {
                long length = objStream.Length;
                while (length > 0L)
                {
                    if (objResponse.IsClientConnected)
                    {
                        int count = objStream.Read(buffer, 0, 0x2710);
                        objResponse.OutputStream.Write(buffer, 0, count);
                        objResponse.Flush();
                        buffer = new byte[0x2711];
                        length -= count;
                    }
                    else
                    {
                        length = -1L;
                    }
                }
            }
            catch (Exception exception1)
            {
                ProjectData.SetProjectError(exception1);
                Exception exception = exception1;
                objResponse.Write("Error : " + exception.Message);
                ProjectData.ClearProjectError();
            }
            finally
            {
                if (!Information.IsNothing(objStream))
                {
                    objStream.Close();
                }
            }
        }
        /// <summary>
        /// Upload file len Server
        /// </summary>
        /// <param name="file"></param>
        /// <param name="fileName"></param>
        /// <param name="folderUpload">Thu muc chua file upload</param>
        /// <param name="extension">kieu dinh dang file</param>
        /// <param name="limitContentLenght">dung luong file cho phep</param>
        /// <returns>
        /// return -1: sai duong dan chua file,0: Upload thanh cong,1: File da ton tai, khong the upload toi server,2: Tep tin co dung luong lon hon cho phep ,3: Tep tin khong dung dinh dang       
        /// </returns>
        public static int UploadFile(HttpPostedFile file, string fileName, string folderUpload, string[] extension, int limitContentLenght, bool overwrite)
        {
            try
            {
                if (file.ContentLength > 0 && !Fsy_Null.IsNull(file.FileName) && IsContentType(file.FileName, extension))
                {
                    if (file.ContentLength <= limitContentLenght)
                    {
                        string filePath = HttpContext.Current.Server.MapPath(GetVitualFilePath(folderUpload)) + fileName;
                        if (File.Exists(filePath) && !overwrite)
                        {
                            return 1;
                        }
                        file.SaveAs(filePath);
                        return 0;
                    }
                    return 2;
                }
                return 3;
            }
            catch
            {
                return -1;
            }
        }
        /// <summary>
        /// Lay tat ca cac File co kieu chi dinh trong 1 thu muc
        /// </summary>
        /// <param name="folderPath">Thu muc can lay File</param>
        /// <param name="fileContentType">Kieu File can lay</param>
        /// <param name="arrResult">Mang chua danh sach cac File tra ve</param>
        private static void FilesFromFolder(string folderPath, string fileContentType, ArrayList arrResult)
        {
            FileInfo[] arrFileInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath(folderPath)).GetFiles();
            if (arrFileInfo.Length <= 0)
                return;
            foreach (FileInfo fileInfo in arrFileInfo)
            {
                if (fileInfo.Extension != ".db")
                {
                    if (fileContentType == ".*")
                    {
                        Fsy_FileInfo fileItem = new Fsy_FileInfo(fileInfo.Name, folderPath + fileInfo.Name, fileInfo.Length, fileInfo.LastWriteTime, fileInfo.LastAccessTime);
                        arrResult.Add(fileItem);
                    }
                    else if (fileInfo.Extension != ".db" && fileInfo.Extension == fileContentType)
                    {
                        Fsy_FileInfo fileItem = new Fsy_FileInfo(fileInfo.Name, folderPath + fileInfo.Name, fileInfo.Length, fileInfo.LastWriteTime, fileInfo.LastAccessTime);
                        arrResult.Add(fileItem);
                    }
                }
                else
                    fileInfo.Delete();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="fileContentType"></param>
        /// <param name="arrResult"></param>
        private static void GetSubFolder(string folderPath, string fileContentType, ArrayList arrResult)
        {
            string path = folderPath;
            DirectoryInfo[] arrDirectoryInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath(folderPath)).GetDirectories();
            if (arrDirectoryInfo != null && arrDirectoryInfo.Length > 0)
            {
                foreach (DirectoryInfo dirInfo in arrDirectoryInfo)
                {
                    string pa = path + dirInfo.Name + "/";
                    GetFilesFromFolder(pa, fileContentType, arrResult);
                }
            }
        }
        /// <summary>
        /// Duyet file
        /// </summary>
        /// <param name="folderPath">duong dan thu muc can duyet</param>
        /// <param name="fileContentType">Kieu file can duyet, neu ".*" thi duyet tat ca cac file</param>
        /// <param name="arrResult">Mang ket qua tra ve</param>
        public static void GetFilesFromFolder(string folderPath, string fileContentType, ArrayList arrResult)
        {
            string path = folderPath;
            FilesFromFolder(path, fileContentType, arrResult);
            DirectoryInfo[] arrDirectoryInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath(path)).GetDirectories();
            if (arrDirectoryInfo != null && arrDirectoryInfo.Length > 0)
            {
                foreach (DirectoryInfo dirInfo in arrDirectoryInfo)
                {
                    string pa = path + dirInfo.Name + "/";
                    FilesFromFolder(pa, fileContentType, arrResult);
                    GetSubFolder(pa, fileContentType, arrResult);
                }
            }
            return;
        }
        /// <summary>
        /// Xoa thu muc
        /// </summary>
        /// <param name="folderPath">Duong dan thu muc can xoa</param>
        public static void DeleteFolder(string folderPath)
        {
            string path = folderPath;
            DeleteFilesFromFolder(path);
            DirectoryInfo[] arrDirectoryInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath(path)).GetDirectories();
            if (arrDirectoryInfo != null && arrDirectoryInfo.Length > 0)
            {
                foreach (DirectoryInfo dirInfo in arrDirectoryInfo)
                {
                    string pa = path + dirInfo.Name + "/";
                    DeleteFilesFromFolder(pa);
                    DeleteSubFolder(pa);
                }
                DirectoryInfo dir = new DirectoryInfo(HttpContext.Current.Server.MapPath(path));
                dir.Delete(true);
            }
            else
            {
                DirectoryInfo dirParent = new DirectoryInfo(HttpContext.Current.Server.MapPath(path));
                dirParent.Delete(true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="folderPath"></param>
        private static void DeleteFilesFromFolder(string folderPath)
        {
            FileInfo[] arrFileInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath(GetVitualFilePath(folderPath))).GetFiles();
            foreach (FileInfo fileInfo in arrFileInfo)
            {
                fileInfo.Delete();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="folderPath"></param>
        private static void DeleteSubFolder(string folderPath)
        {
            DeleteFilesFromFolder(folderPath);
            DirectoryInfo[] arrDirectoryInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath(folderPath)).GetDirectories();
            if (arrDirectoryInfo != null && arrDirectoryInfo.Length > 0)
            {
                foreach (DirectoryInfo dirInfo in arrDirectoryInfo)
                {
                    folderPath += dirInfo.Name + "/";
                    DeleteFilesFromFolder(folderPath);
                    DeleteSubFolder(folderPath);
                    DirectoryInfo dir = new DirectoryInfo(HttpContext.Current.Server.MapPath(folderPath));
                    dir.Delete(true);
                }
            }
            else
            {
                DirectoryInfo dirParent = new DirectoryInfo(HttpContext.Current.Server.MapPath(folderPath));
                dirParent.Delete(true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath"></param>
        public static void DeleteFile(string filePath)
        {
            string strFilePath = HttpContext.Current.Server.MapPath(filePath);
            if (File.Exists(strFilePath))
                File.Delete(strFilePath);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath"></param>
        public static void DeleteFiles(string[] filePath)
        {
            try
            {
                foreach (string file in filePath)
                {
                    string strFilePath = HttpContext.Current.Server.MapPath(file);
                    if (File.Exists(strFilePath))
                        File.Delete(strFilePath);
                }
            }
            catch
            {
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string GetVitualFilePath(string filePath)
        {
            return HttpRuntime.AppDomainAppVirtualPath + "/" + filePath;
        }
    }
}
